extends Control
class_name PlayerHUD

## 玩家HUD界面
## 显示玩家的血条、经验条和等级信息

@onready var hp_bar: ProgressBar = $VBoxContainer/HPContainer/HPBar
@onready var hp_label: Label = $VBoxContainer/HPContainer/HPLabel
@onready var phantom_beasts_hp_container: VBoxContainer = $VBoxContainer/PhantomBeastsHPContainer
@onready var mp_bar: ProgressBar = $VBoxContainer/MPContainer/MPBar
@onready var mp_label: Label = $VBoxContainer/MPContainer/MPLabel
@onready var exp_bar: ProgressBar = $VBoxContainer/ExpContainer/ExpBar
@onready var exp_label: Label = $VBoxContainer/ExpContainer/ExpLabel
@onready var level_label: Label = $VBoxContainer/LevelLabel
@onready var level_up_animation: AnimationPlayer = $LevelUpAnimation

# 功能按钮引用
@onready var character_info_button: Button = $ButtonContainer/CharacterInfoButton
@onready var inventory_button: Button = $ButtonContainer/InventoryButton
@onready var phantom_beast_button: Button = $ButtonContainer/PhantomBeastButton
@onready var settings_button: Button = $ButtonContainer/SettingsButton
@onready var auto_encounter_button: Button = $ButtonContainer/AutoEncounterButton
@onready var return_home_button: Button = $ButtonContainer/ReturnHomeButton

# UI窗口引用
var inventory_window: InventoryWindow = null
var character_stats_window: CharacterStatsWindow = null
var phantom_beast_window: Window = null
var auto_sell_settings_window: Window = null

# 自动遇怪相关变量
var auto_encounter_enabled: bool = false
var auto_move_timer: Timer = null
var auto_move_direction: int = 0  # 0=上, 1=下, 2=左, 3=右
var move_directions: Array[Vector2] = [Vector2.UP, Vector2.DOWN, Vector2.LEFT, Vector2.RIGHT]
var auto_move_interval: float = 1.0  # 自动移动间隔时间（秒）
var previous_battle_speed: float = 1.0  # 保存自动遇怪前的战斗速度

func _ready():
	# 连接玩家属性管理器的信号
	if PlayerStatsManager != null:
		PlayerStatsManager.health_changed.connect(_on_health_changed)
		PlayerStatsManager.mana_changed.connect(_on_mana_changed)
		PlayerStatsManager.experience_changed.connect(_on_experience_changed)
		PlayerStatsManager.level_up.connect(_on_level_up)
		
		# 初始化显示
		_update_health_display(PlayerStatsManager.get_current_hp(), PlayerStatsManager.get_max_hp())
		_update_mana_display(PlayerStatsManager.get_current_mp(), PlayerStatsManager.get_max_mp())
		_update_experience_display(PlayerStatsManager.get_current_exp(), PlayerStatsManager.get_exp_to_next())
		_update_level_display(PlayerStatsManager.get_level())
	
	# 连接幻兽管理器的信号
	if PhantomBeastManager != null:
		PhantomBeastManager.formation_changed.connect(_on_phantom_beast_formation_changed)
		PhantomBeastManager.phantom_beast_health_changed.connect(_on_phantom_beast_health_changed)
		# 初始化幻兽生命值显示
		_update_phantom_beasts_hp_display()
	
	# 连接战斗管理器信号
	if BattleManager != null:
		BattleManager.battle_started.connect(_on_battle_started)
		BattleManager.battle_ended.connect(_on_battle_ended)
	
	# 初始化自动移动计时器
	_initialize_auto_move_timer()
	
	# 连接按钮信号
	_connect_button_signals()
	
	# 初始化UI窗口
	_initialize_windows()
	
	# 恢复自动遇怪状态
	_restore_auto_encounter_state()

func _on_health_changed(current_hp: int, max_hp: int):
	"""生命值变化时更新显示"""
	_update_health_display(current_hp, max_hp)
	
	# 如果玩家死亡，自动关闭自动遇怪功能
	if current_hp <= 0 and auto_encounter_enabled:
		print("玩家死亡，自动遇怪已关闭")
		_disable_auto_encounter()

func _on_mana_changed(current_mp: int, max_mp: int):
	"""蓝量变化时更新显示"""
	_update_mana_display(current_mp, max_mp)

func _on_experience_changed(current_exp: int, exp_to_next: int):
	"""经验值变化时更新显示"""
	_update_experience_display(current_exp, exp_to_next)

func _on_level_up(new_level: int):
	"""升级时更新显示并播放动画"""
	_update_level_display(new_level)
	
	# 播放升级动画
	if level_up_animation != null:
		level_up_animation.play("level_up")

func _on_phantom_beast_formation_changed(_active_beasts: Array):
	"""幻兽队伍变化时更新显示"""
	_update_phantom_beasts_hp_display()

func _on_phantom_beast_health_changed(_beast_id: String, _current_hp: int, _max_hp: int):
	"""幻兽生命值变化时更新显示"""
	_update_phantom_beasts_hp_display()

func _update_health_display(current_hp: int, max_hp: int):
	"""更新生命值显示"""
	if hp_bar != null:
		hp_bar.max_value = max_hp
		hp_bar.value = current_hp
		
		# 根据生命值百分比改变颜色
		var hp_percentage = float(current_hp) / float(max_hp)
		if hp_percentage > 0.6:
			hp_bar.modulate = Color.GREEN
		elif hp_percentage > 0.3:
			hp_bar.modulate = Color.YELLOW
		else:
			hp_bar.modulate = Color.RED
	
	if hp_label != null:
		hp_label.text = "HP: %d/%d" % [current_hp, max_hp]

func _update_mana_display(current_mp: int, max_mp: int):
	"""更新蓝量显示"""
	if mp_bar != null:
		mp_bar.max_value = max_mp
		mp_bar.value = current_mp
	
	if mp_label != null:
		mp_label.text = "MP: %d/%d" % [current_mp, max_mp]

func _update_experience_display(current_exp: int, exp_to_next: int):
	"""更新经验值显示"""
	if exp_bar != null:
		exp_bar.max_value = exp_to_next
		exp_bar.value = current_exp
	
	if exp_label != null:
		exp_label.text = "EXP: %d/%d" % [current_exp, exp_to_next]

func _update_level_display(level: int):
	"""更新等级显示"""
	if level_label != null:
		level_label.text = "Lv.%d" % level

func _update_phantom_beasts_hp_display():
	"""更新幻兽生命值显示"""
	if phantom_beasts_hp_container == null or PhantomBeastManager == null:
		return
	
	# 清除现有的幻兽生命值显示
	for child in phantom_beasts_hp_container.get_children():
		child.queue_free()
	
	# 获取当前上阵的幻兽
	var active_formation = PhantomBeastManager.get_active_formation_ids()
	if active_formation.is_empty():
		return
	
	# 为每个上阵的幻兽创建生命值显示
	for i in range(active_formation.size()):
		var beast_id = active_formation[i]
		if beast_id == "":
			continue
		
		var beast_data = PhantomBeastManager.get_phantom_beast_full_info(beast_id)
		if beast_data.is_empty():
			continue
		
		# 创建幻兽生命值容器
		var beast_hp_container = HBoxContainer.new()
		phantom_beasts_hp_container.add_child(beast_hp_container)
		
		# 创建幻兽名称标签
		var beast_name_label = Label.new()
		var display_name = PhantomBeastManager.get_phantom_beast_display_name(beast_id)
		beast_name_label.text = display_name + ":"
		beast_name_label.size_flags_horizontal = Control.SIZE_SHRINK_CENTER
		beast_name_label.custom_minimum_size.x = 60
		beast_hp_container.add_child(beast_name_label)
		
		# 获取幻兽当前生命值信息
		var stats = PhantomBeastManager.get_phantom_beast_stats(beast_id)
		var current_hp = beast_data.get("current_hp", stats.max_hp)
		var max_hp = stats.max_hp
		var is_alive = beast_data.get("is_alive", true)
		
		# 创建生命值标签
		var beast_hp_label = Label.new()
		if is_alive:
			beast_hp_label.text = "HP: %d/%d" % [current_hp, max_hp]
			# 根据生命值百分比设置颜色
			var hp_percentage = float(current_hp) / float(max_hp) if max_hp > 0 else 0.0
			if hp_percentage > 0.6:
				beast_hp_label.add_theme_color_override("font_color", Color.GREEN)
			elif hp_percentage > 0.3:
				beast_hp_label.add_theme_color_override("font_color", Color.YELLOW)
			else:
				beast_hp_label.add_theme_color_override("font_color", Color.ORANGE)
		else:
			beast_hp_label.text = "HP: 0/%d (死亡)" % max_hp
			beast_hp_label.add_theme_color_override("font_color", Color.RED)
		
		beast_hp_label.size_flags_horizontal = Control.SIZE_EXPAND_FILL
		beast_hp_container.add_child(beast_hp_label)
		
		# 创建生命值进度条
		var beast_hp_bar = ProgressBar.new()
		beast_hp_bar.max_value = max_hp
		beast_hp_bar.value = current_hp if is_alive else 0
		beast_hp_bar.size_flags_horizontal = Control.SIZE_EXPAND_FILL
		beast_hp_bar.custom_minimum_size.x = 100
		
		# 根据生命值状态设置进度条颜色
		if is_alive:
			var hp_percentage = float(current_hp) / float(max_hp) if max_hp > 0 else 0.0
			if hp_percentage > 0.6:
				beast_hp_bar.modulate = Color.GREEN
			elif hp_percentage > 0.3:
				beast_hp_bar.modulate = Color.YELLOW
			else:
				beast_hp_bar.modulate = Color.ORANGE
		else:
			beast_hp_bar.modulate = Color.RED
		
		beast_hp_container.add_child(beast_hp_bar)

func show_damage_number(damage: int, display_pos: Vector2):
	"""显示伤害数字"""
	var damage_label = Label.new()
	damage_label.text = "-" + str(damage)
	damage_label.add_theme_color_override("font_color", Color.RED)
	damage_label.position = display_pos
	add_child(damage_label)
	
	# 动画效果
	var tween = create_tween()
	tween.parallel().tween_property(damage_label, "position", display_pos + Vector2(0, -50), 1.0)
	tween.parallel().tween_property(damage_label, "modulate:a", 0.0, 1.0)
	tween.tween_callback(damage_label.queue_free)

func show_heal_number(heal: int, display_pos: Vector2):
	"""显示治疗数字"""
	var heal_label = Label.new()
	heal_label.text = "+" + str(heal)
	heal_label.add_theme_color_override("font_color", Color.GREEN)
	heal_label.position = display_pos
	add_child(heal_label)
	
	# 动画效果
	var tween = create_tween()
	tween.parallel().tween_property(heal_label, "position", display_pos + Vector2(0, -50), 1.0)
	tween.parallel().tween_property(heal_label, "modulate:a", 0.0, 1.0)
	tween.tween_callback(heal_label.queue_free)

func show_exp_number(experience: int, display_pos: Vector2):
	"""显示经验值数字"""
	var experience_label = Label.new()
	experience_label.text = "+" + str(experience) + " EXP"
	experience_label.add_theme_color_override("font_color", Color.YELLOW)
	experience_label.position = display_pos
	add_child(experience_label)
	
	# 动画效果
	var tween = create_tween()
	tween.parallel().tween_property(experience_label, "position", display_pos + Vector2(0, -50), 1.0)
	tween.parallel().tween_property(experience_label, "modulate:a", 0.0, 1.0)
	tween.tween_callback(experience_label.queue_free)

func _connect_button_signals():
	"""连接按钮信号"""
	if character_info_button != null:
		character_info_button.pressed.connect(_on_character_info_pressed)
		# 禁用按钮焦点，避免与角色移动键冲突
		character_info_button.focus_mode = Control.FOCUS_NONE
	if inventory_button != null:
		inventory_button.pressed.connect(_on_inventory_pressed)
		# 禁用按钮焦点，避免与角色移动键冲突
		inventory_button.focus_mode = Control.FOCUS_NONE

	if phantom_beast_button != null:
		phantom_beast_button.pressed.connect(_on_phantom_beast_pressed)
		# 禁用按钮焦点，避免与角色移动键冲突
		phantom_beast_button.focus_mode = Control.FOCUS_NONE
	if settings_button != null:
		settings_button.pressed.connect(_on_settings_pressed)
		# 禁用按钮焦点，避免与角色移动键冲突
		settings_button.focus_mode = Control.FOCUS_NONE
	if auto_encounter_button != null:
		auto_encounter_button.pressed.connect(_on_auto_encounter_pressed)
		# 禁用按钮焦点，避免与角色移动键冲突
		auto_encounter_button.focus_mode = Control.FOCUS_NONE
	if return_home_button != null:
		return_home_button.pressed.connect(_on_return_home_pressed)
		# 禁用按钮焦点，避免与角色移动键冲突
		return_home_button.focus_mode = Control.FOCUS_NONE

func _on_character_info_pressed():
	# 停止自动遇怪功能
	_disable_auto_encounter()
	print("已停止自动遇怪")
	
	"""角色信息按钮点击处理"""
	if character_stats_window != null:
		character_stats_window.toggle_visibility()

func _on_inventory_pressed():
	# 停止自动遇怪功能
	_disable_auto_encounter()
	print("已停止自动遇怪")
	"""背包按钮点击处理"""
	if inventory_window != null:
		inventory_window.toggle_visibility()



func _on_phantom_beast_pressed():
	# 停止自动遇怪功能
	_disable_auto_encounter()
	print("已停止自动遇怪")
	"""幻兽系统按钮点击处理"""
	if phantom_beast_window != null:
		phantom_beast_window.toggle_visibility()
		phantom_beast_window._auto_sort_beasts()
	else:
		print("幻兽窗口未初始化")

func _on_settings_pressed():
	# 停止自动遇怪功能
	_disable_auto_encounter()
	print("已停止自动遇怪")
	"""设置按钮点击处理"""
	print("设置按钮被点击")
	if auto_sell_settings_window != null:
		auto_sell_settings_window.toggle_visibility()

func _on_return_home_pressed():
	"""回城按钮点击处理"""
	print("回城按钮被点击")
	# 回城前停止自动遇怪功能
	_disable_auto_encounter()
	print("回城：已停止自动遇怪")
	
	# 回到场景1的初始位置
	# 清除玩家位置数据，确保使用默认位置
	if PlayerManager != null:
		PlayerManager.player_data["position"] = Vector2.ZERO
	# 切换到场景1
	get_tree().change_scene_to_file("res://scene/scene1.tscn")

func _initialize_windows():
	"""初始化UI窗口"""
	# 创建背包窗口
	var inventory_scene = preload("res://ui/inventory_window.tscn")
	inventory_window = inventory_scene.instantiate()
	get_tree().root.add_child(inventory_window)
	inventory_window.hide()
	# 设置PlayerHUD引用
	inventory_window.player_hud = self
	
	# 创建角色属性窗口
	var character_stats_scene = preload("res://ui/character_stats_window.tscn")
	character_stats_window = character_stats_scene.instantiate()
	get_tree().root.add_child(character_stats_window)
	character_stats_window.hide()
	# 设置PlayerHUD引用
	character_stats_window.player_hud = self
	
	# 创建幻兽系统窗口
	var phantom_beast_scene = preload("res://ui/phantom_beast_ui.tscn")
	phantom_beast_window = phantom_beast_scene.instantiate()
	get_tree().root.add_child(phantom_beast_window)
	phantom_beast_window.hide()
	# 设置PlayerHUD引用
	phantom_beast_window.player_hud = self
	
	# 创建自动售卖设置窗口
	var auto_sell_settings_scene = preload("res://ui/auto_sell_settings.tscn")
	auto_sell_settings_window = auto_sell_settings_scene.instantiate()
	get_tree().root.add_child(auto_sell_settings_window)
	auto_sell_settings_window.hide()
	# 设置PlayerHUD引用
	auto_sell_settings_window.player_hud = self

func _initialize_auto_move_timer():
	"""初始化自动移动计时器"""
	auto_move_timer = Timer.new()
	auto_move_timer.wait_time = auto_move_interval
	auto_move_timer.timeout.connect(_on_auto_move_timeout)
	add_child(auto_move_timer)

func _on_auto_encounter_pressed():
	"""自动遇怪按钮点击处理"""
	auto_encounter_enabled = auto_encounter_button.button_pressed
	
	if auto_encounter_enabled:
		print("自动遇怪已开启")
		auto_encounter_button.text = "停止遇怪"
		# 保存当前战斗速度
		if PlayerManager != null:
			previous_battle_speed = PlayerManager.get_battle_speed_multiplier()
			# 设置战斗速度为20倍
			PlayerManager.set_battle_speed_multiplier(20.0)
			print("自动遇怪：战斗速度已设置为20倍")
		# 开始自动移动
		_start_auto_movement()
	else:
		print("自动遇怪已关闭")
		auto_encounter_button.text = "自动遇怪"
		# 恢复之前的战斗速度
		if PlayerManager != null:
			PlayerManager.set_battle_speed_multiplier(previous_battle_speed)
			print("自动遇怪：战斗速度已恢复为%.1f倍" % previous_battle_speed)
		# 停止自动移动
		_stop_auto_movement()
	
	# 保存自动遇怪状态到PlayerManager
	_save_auto_encounter_state()

func _start_auto_movement():
	"""开始自动移动"""
	if auto_move_timer != null:
		auto_move_timer.start()

func _stop_auto_movement():
	"""停止自动移动"""
	if auto_move_timer != null:
		auto_move_timer.stop()

func _on_auto_move_timeout():
	"""自动移动计时器超时处理"""
	if not auto_encounter_enabled:
		return
	
	# 检查玩家是否死亡
	if PlayerStatsManager != null and PlayerStatsManager.get_current_hp() <= 0:
		print("玩家死亡，自动遇怪已关闭")
		_disable_auto_encounter()
		return
	
	# 获取当前玩家
	var player = null
	if PlayerManager != null:
		player = PlayerManager.get_current_player()
	
	if player == null or not player.has_method("attempt_move"):
		return
	
	# 检查玩家是否可以移动
	if not player.can_move or player.is_moving:
		return
	
	# 循环移动方向：上->下->左->右
	var direction = move_directions[auto_move_direction]
	player.attempt_move(direction)
	
	# 切换到下一个方向
	auto_move_direction = (auto_move_direction + 1) % move_directions.size()

func _disable_auto_encounter():
	"""禁用自动遇怪功能"""
	auto_encounter_enabled = false
	if auto_encounter_button != null:
		auto_encounter_button.button_pressed = false
		auto_encounter_button.text = "自动遇怪"
	# 恢复之前的战斗速度
	if PlayerManager != null:
		PlayerManager.set_battle_speed_multiplier(previous_battle_speed)
		print("自动遇怪：战斗速度已恢复为%.1f倍" % previous_battle_speed)
	_stop_auto_movement()
	
	# 保存自动遇怪状态到PlayerManager
	_save_auto_encounter_state()

func _on_battle_started():
	"""战斗开始时的处理"""
	print("战斗开始，暂停自动移动")
	# 暂停自动移动，但保持自动遇怪状态
	if auto_move_timer != null and auto_move_timer.time_left > 0:
		auto_move_timer.stop()

func _on_battle_ended(victory: bool):
	"""战斗结束时的处理"""
	print("战斗结束，victory: ", victory)
	# 如果自动遇怪仍然启用，恢复自动移动
	if auto_encounter_enabled:
		print("恢复自动遇怪移动")
		# 延迟一小段时间再开始移动，确保场景切换完成
		get_tree().create_timer(0.5).timeout.connect(_resume_auto_movement)

func _resume_auto_movement():
	"""恢复自动移动"""
	if auto_encounter_enabled and auto_move_timer != null:
		auto_move_timer.start()

func _restore_auto_encounter_state():
	"""从PlayerManager恢复自动遇怪状态"""
	if PlayerManager != null and PlayerManager.player_data.has("auto_encounter_enabled"):
		auto_encounter_enabled = PlayerManager.player_data["auto_encounter_enabled"]
		if auto_encounter_button != null:
			auto_encounter_button.button_pressed = auto_encounter_enabled
			if auto_encounter_enabled:
				auto_encounter_button.text = "停止遇怪"
				# 恢复战斗速度设置
				if PlayerManager.player_data.has("previous_battle_speed"):
					previous_battle_speed = PlayerManager.player_data["previous_battle_speed"]
				else:
					previous_battle_speed = 1.0
				PlayerManager.set_battle_speed_multiplier(20.0)
				_start_auto_movement()
			else:
				auto_encounter_button.text = "自动遇怪"

func _save_auto_encounter_state():
	"""保存自动遇怪状态到PlayerManager"""
	if PlayerManager != null:
		PlayerManager.player_data["auto_encounter_enabled"] = auto_encounter_enabled
		PlayerManager.player_data["previous_battle_speed"] = previous_battle_speed
		PlayerManager.save_player_data()
